package com.spark.incoicings.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spark.incoicings.service.*;
import com.spark.invoicings.entity.*;
import com.spark.invoicings.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 采购付款核销
 *
 */
@RestController
@RequestMapping("/SalesReceipt")
public class PaymentVerificationController {
    @Resource
    private PaymentVerificationService ps;
    @Resource
    private ProcuredSupplierService pss;
    @Resource
    private PaymentService pays;
    @Resource
    private OrderService os;
    @Resource
    private PurchaseDetailService pds;
    @Resource
    private SupplierStatementDetailService ssds;
    @Resource
    private ReceivablePayableDetailService rps;
    @Resource
    private SupplierStatementService sss;
    @Resource
    private ProductService productService;
    @Resource
    private DictDataService ds;


    /**
     * 采购付款核销条件分页查询
     * */
    @GetMapping("/selectPaymentVerification")
    public Result selectPaymentVerification(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize,
            @RequestParam(value = "verifier", required = false) String verifier,
            @RequestParam(value = "supplierId", required = false) Integer supplierId) {

        // 开始分页
        PageHelper.startPage(pageNum, pageSize);

        // 准备查询参数
        Map<String, Object> map = new HashMap<>();
        map.put("verifier", verifier);
        map.put("supplierId", supplierId);
        PageHelper.orderBy("payment_verification_id desc");
        // 获取 PaymentVerification 实体列表
        List<PaymentVerification> list = ps.selectAll(map);

        // 获取并设置相关实体到 PaymentVerification 对象中
        for (PaymentVerification p : list) {
            // 获取相关实体并进行空指针检查
            if (p.getSupplierId() != null) {
                p.setProcuredSupplier(pss.getById(p.getSupplierId()));
            }
            if (p.getPaymentId() != null) {
                p.setPayment(pays.getById(p.getPaymentId()));
            }
            if (p.getOrderId() != null) {
                p.setOrder(os.getById(p.getOrderId()));
            }
            if (p.getPaymentDetailsId() != null) {
                p.setPurchaseDetail(pds.getById(p.getPaymentDetailsId()));
                PurchaseDetail purchaseDetail = p.getPurchaseDetail();
                if (purchaseDetail != null && purchaseDetail.getProductId() != null) {
                    purchaseDetail.setProduct(productService.getById(purchaseDetail.getProductId()));
                }
            }
            if (p.getBillDetailId() != null) {
                p.setStatementDetail(ssds.getById(p.getBillDetailId()));
            }
            if (p.getPayableDetailId() != null) {
                p.setReceivablePayableDetail(rps.getById(p.getPayableDetailId()));
            }
        }

        // 创建 PageInfo 对象以获取分页信息
        PageInfo<PaymentVerification> page = new PageInfo<>(list);

        // 返回带有分页数据的成功响应
        return Result.success(200, "success", page);
    }



    /**
     *根据供应商id查询采购订单和明细、供应商对账单和明细、应付明细
     * */
    @GetMapping("/selectOrder")
    public Result selectId(Integer supplierId){
        Map<String, Object> result = new HashMap<>();
        result.put("payments",pays.selectPayment(supplierId));

        List<Order> orders = os.selectOrderId(supplierId);
        for (Order o:orders){
            o.setPurchaseDetails(pds.selectOrderDetail(o.getPurchaseOrderId()));
        }
        result.put("orders",orders);
        List<SupplierStatement> supplierStatements = sss.selectSupplierStatement(supplierId);
        for (SupplierStatement s:supplierStatements){
            s.setStatementDetails(ssds.selectSupplierStatementDetail(s.getSupplierStatementId()));
        }
        result.put("supplierStatements",supplierStatements);
        List<ReceivablePayableDetail> list = rps.selectPayment(supplierId);
        for (ReceivablePayableDetail r:list){
            r.setProduct(productService.getById(r.getProductId()));
            r.setDictData(Arrays.asList(ds.getById(r.getSettlementTypeId()), ds.getById(r.getBusinessTypeId())));
        }
        result.put("payableDetails", list);
        return Result.success(200, "success", result);
    }

    /**
     * 根据核销id查询采购付款核销
     * */
    @GetMapping("/PaymentVerificationById")
    public Result PaymentVerificationById(Integer paymentVerificationId){
        PaymentVerification p = ps.getById(paymentVerificationId);
        // 获取相关实体并进行空指针检查
        if (p.getSupplierId() != null) {
            p.setProcuredSupplier(pss.getById(p.getSupplierId()));
        }
        if (p.getPaymentId() != null) {
            p.setPayment(pays.getById(p.getPaymentId()));
        }
        if (p.getOrderId() != null) {
            p.setOrder(os.getById(p.getOrderId()));
        }
        if (p.getPaymentDetailsId() != null) {
            p.setPurchaseDetail(pds.getById(p.getPaymentDetailsId()));
            PurchaseDetail purchaseDetail = p.getPurchaseDetail();
            if (purchaseDetail != null && purchaseDetail.getProductId() != null) {
                purchaseDetail.setProduct(productService.getById(purchaseDetail.getProductId()));
            }
        }
        if (p.getBillDetailId() != null) {
            p.setStatementDetail(ssds.getById(p.getBillDetailId()));
        }
        if (p.getPayableDetailId() != null) {
            p.setReceivablePayableDetail(rps.getById(p.getPayableDetailId()));
        }
        return Result.success(200, "success", p);
    }


    /**
     * 添加采购付款核销
     * */
    @PostMapping("/savePaymentVerification")
    @Transactional
    public Result savePaymentVerification(@RequestBody PaymentVerification paymentVerification){
        Order order = os.getById(paymentVerification.getOrderId());
        double yhk=paymentVerification.getVerificationAmount()+order.getReceivedAmount();//已回款金额
        double dhk=order.getTotalAmount()-yhk;//待回款金额
        order.setPaidAmount(yhk);
        order.setPendingPaymentAmount(dhk);
        os.updateById(order);
        ps.save(paymentVerification);
        return Result.success();
    }

    /**
     * 修改采购付款核销
     * */
    @PostMapping("/updatePaymentVerification")
    public Result updatePaymentVerification(@RequestBody PaymentVerification paymentVerification){
        ps.updateById(paymentVerification);
        return Result.success();
    }
}
